package org.hj.modules.chapter.controller;

import java.util.*;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import org.apache.shiro.SecurityUtils;
import org.hj.common.annotation.AutoLog;
import org.hj.common.api.vo.Result;
import org.hj.common.system.api.ISysBaseAPI;
import org.hj.common.system.query.QueryGenerator;
import org.hj.common.system.util.Excel.ExportParams;
import org.hj.common.system.util.Excel.HjEntityExcelView;
import org.hj.common.system.util.Excel.NormalExcelConstants;
import org.hj.common.system.vo.LoginUser;
import org.hj.common.util.oConvertUtils;
import org.hj.modules.AcStartController;
import org.hj.modules.act.leave.entity.OaLeaveBill;
import org.hj.modules.chapter.entity.ActeChapter;
import org.hj.modules.chapter.service.IActeChapterService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Slf4j
@Api(tags = "公章管理")
@RestController
@RequestMapping("/acteChapter")
public class ActeChapterController extends AcStartController {
	@Autowired
	private IActeChapterService acteChapterService;
	/**
	 * 分页列表查询
	 * 
	 * @param acteChapter
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "公章管理-分页列表查询")
	@ApiOperation(value = "公章管理-分页列表查询", notes = "公章管理-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ActeChapter>> queryPageList(ActeChapter acteChapter,
			@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
		Result<IPage<ActeChapter>> result = new Result<IPage<ActeChapter>>();
		QueryWrapper<ActeChapter> queryWrapper = QueryGenerator.initQueryWrapper(acteChapter, req.getParameterMap());
		Page<ActeChapter> page = new Page<ActeChapter>(pageNo, pageSize);
		IPage<ActeChapter> pageList = acteChapterService.page(page, queryWrapper);
		result.setSuccess(true);
		result.setResult(pageList);
		return result;
	}

	/**
	 * 添加
	 * 
	 * @param acteChapter
	 * @return
	 */
	@AutoLog(value = "公章管理-添加")
	@ApiOperation(value = "公章管理-添加", notes = "公章管理-添加")
	@PostMapping(value = "/add")
	public Result<ActeChapter> add(@RequestBody ActeChapter acteChapter) {
		Result<ActeChapter> result = new Result<ActeChapter>();
		try {
			acteChapterService.save(acteChapter);
			result.success("添加成功！");
			result.setResult(acteChapter);
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;
	}

	@RequestMapping(value = "/submit")
	@ResponseBody
	public Object submit(@RequestParam(name = "id", required = true) String id) {
		String taskId=null;
		String ProId=null;
		Result<ActeChapter> result = new Result<ActeChapter>();
		// 获取当前登录人信息
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		// 通过id抓取公章申请的信息
		ActeChapter acteChapter = acteChapterService.getById(id);

		if (AppStatus.contains(acteChapter.getAppstatus())) {
			return result.error500("待处理中,不能重复提交");
		}

		try {
			/** 工作流的操作 **/
			Map<String, Object> map = new LinkedHashMap<String, Object>();
			map.put("id", acteChapter.getId()); // 
			map.put("申请人", acteChapter.getCreateName()); // 当前用户的姓名
			map.put("所属部门", GetDeparmentText(acteChapter.getSysOrgCode()));
			map.put("单证类型", GetDicDocumentText(acteChapter.getType()));
			map.put("盖章说明", acteChapter.getReason());
			map.put("是否加急", GetDicStatus_enText(acteChapter.getDispatch()));
			map.put("申请时间", acteChapter.getCreateTime());
			map.put("username", sysUser.getUsername()); // 指派代理人为当前用户
		
			if (acteChapter.getAppstatus().equals("1"))
			{
		        ProId=startProcessInstanceByKeyHasVariables("acte_chapter", map); // 启动流程实例(请假单流程)通过KEY
			    acteChapter.setProcInstId(ProId);
			}
			else
			{
				ProId=acteChapter.getProcInstId();
			}
			//根据ProId 查询任务ID_
			Map<Object, Object> taskMap=getActRuTaskById(ProId);
			if (null==taskMap) return result.error500("未找到流程任务编号");
		    taskId=taskMap.get("ID_").toString();
						
			//提交申请
		    Map<String, Object> submitMap =new LinkedHashMap<String, Object>();
		    submitMap.put("单证申请", "【已提交】");		//审批结果
			setVariablesByTaskIdAsMap(taskId,submitMap);			//设置流程变量
			setVariablesByTaskId(taskId,"RESULT","批准");
			completeMyPersonalTask(taskId);
			//修改单证状态
			acteChapter.setAppstatus("2");
			acteChapterService.updateById(acteChapter); // 记录存入数据库
			// zmap.put("ASSIGNEE_",sysUser.getUsername()); 用于给待办人发送新任务消息
			result.success("操作成功!");
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			result.error500("操作失败");
		}
		return result;
	}

	/**
	 * 编辑
	 * 
	 * @param acteChapter
	 * @return
	 */
	@AutoLog(value = "公章管理-提交")
	@ApiOperation(value = "公章管理-编辑", notes = "公章管理-编辑")
	@PutMapping(value = "/edit")
	public Result<ActeChapter> edit(@RequestBody ActeChapter acteChapter) {
		Result<ActeChapter> result = new Result<ActeChapter>();
		ActeChapter acteChapterEntity = acteChapterService.getById(acteChapter.getId());

		if (acteChapterEntity == null) {
			result.error500("未找到数据");
		} else {
			if (AppStatus.contains(acteChapterEntity.getAppstatus())) {
				return result.error500("待处理中,不能重复提交");
			}
			boolean ok = acteChapterService.updateById(acteChapter);
			// TODO 返回false说明什么？
			if (ok) {
                result.setResult(acteChapter);
                result.success("修改成功!");
			}
		}

		return result;
	}

	/**
	 * 通过id删除
	 * 
	 * @param id
	 * @return
	 */
	@AutoLog(value = "公章管理-通过id删除")
	@ApiOperation(value = "公章管理-通过id删除", notes = "公章管理-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<ActeChapter> delete(@RequestParam(name = "id", required = true) String id) {
		Result<ActeChapter> result = new Result<ActeChapter>();
		ActeChapter acteChapter = acteChapterService.getById(id);
		if (acteChapter == null) {
			result.error500("未找到数据");
		} else {
			if (AppStatus.contains(acteChapter.getAppstatus())) {
				return result.error500("待处理中,不能重复提交");
			}
			boolean ok = acteChapterService.removeById(id);
			if (ok) {
				result.success("删除成功!");
			}
		}

		return result;
	}

	/**
	 * 批量删除
	 * 
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "公章管理-批量删除")
	@ApiOperation(value = "公章管理-批量删除", notes = "公章管理-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<ActeChapter> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
		Result<ActeChapter> result = new Result<ActeChapter>();
		if (ids == null || "".equals(ids.trim())) {
			result.error500("参数不识别！");
		} else {
			this.acteChapterService.removeByIds(Arrays.asList(ids.split(",")));
			result.success("删除成功!");
		}
		return result;
	}

	/**
	 * 通过id查询
	 * 
	 * @param id
	 * @return
	 */
	@AutoLog(value = "公章管理-通过id查询")
	@ApiOperation(value = "公章管理-通过id查询", notes = "公章管理-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ActeChapter> queryById(@RequestParam(name = "id", required = true) String id) {
		Result<ActeChapter> result = new Result<ActeChapter>();
		ActeChapter acteChapter = acteChapterService.getById(id);
		if (acteChapter == null) {
			result.error500("未找到对应实体");
		} else {
			result.setResult(acteChapter);
			result.setSuccess(true);
		}
		return result;
	}

	/**
	 * 导出excel
	 *
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/exportXls")
	public ModelAndView exportXls(HttpServletRequest request, HttpServletResponse response) {
		// Step.1 组装查询条件
		QueryWrapper<ActeChapter> queryWrapper = null;
		try {
			String paramsStr = request.getParameter("paramsStr");
			if (oConvertUtils.isNotEmpty(paramsStr)) {
				String deString = URLDecoder.decode(paramsStr, "UTF-8");
				ActeChapter acteChapter = JSON.parseObject(deString, ActeChapter.class);
				queryWrapper = QueryGenerator.initQueryWrapper(acteChapter, request.getParameterMap());
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		// Step.2 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new HjEntityExcelView());
		List<ActeChapter> pageList = acteChapterService.list(queryWrapper);
		// 导出文件名称
		mv.addObject(NormalExcelConstants.FILE_NAME, "公章管理列表");
		mv.addObject(NormalExcelConstants.CLASS, ActeChapter.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("公章管理列表数据", "导出人:hj", "导出信息"));
		mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
		return mv;
	}

	/**
	 * 通过excel导入数据
	 *
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
	public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			MultipartFile file = entity.getValue();// 获取上传文件对象
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<ActeChapter> listActeChapters = ExcelImportUtil.importExcel(file.getInputStream(),
						ActeChapter.class, params);
				for (ActeChapter acteChapterExcel : listActeChapters) {
					acteChapterService.save(acteChapterExcel);
				}
				return Result.ok("文件导入成功！数据行数:" + listActeChapters.size());
			} catch (Exception e) {
				log.error(e.getMessage(), e);
				return Result.error("文件导入失败:" + e.getMessage());
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.ok("文件导入失败！");
	}

}
